<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <link rel="manifest" href="/images/manifest.json">
  <meta name="msapplication-config" content="/images/browserconfig.xml">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/pace-js@1/themes/blue/pace-theme-minimal.css">
  <script src="//cdn.jsdelivr.net/npm/pace-js@1/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"daydaychen.github.io","root":"/","scheme":"Gemini","version":"7.7.2","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":true,"lazyload":true,"pangu":true,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":true,"preload":false},"motion":{"enable":true,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="协程 生成器 迭代器 装饰器 Python三大器   迭代器 -&gt; 生成器 -&gt; yield -&gt; greenlet -&gt; gevent  迭代器迭代时访问集合元素的一种方式，迭代器是一个可以记住遍历的位置的对象，迭代器对象从集合的第一个元素开始访问，直到所有的元素被访问完结束。迭代器只能往前不会后退。  可迭代对象  对list、tuple、str、dict、集合等类型的">
<meta property="og:type" content="article">
<meta property="og:title" content="python协程">
<meta property="og:url" content="daydaychen.github.io/2020/03/06/02-%E5%A4%9A%E4%BB%BB%E5%8A%A1-%E5%8D%8F%E7%A8%8B/index.html">
<meta property="og:site_name" content="宁静致远">
<meta property="og:description" content="协程 生成器 迭代器 装饰器 Python三大器   迭代器 -&gt; 生成器 -&gt; yield -&gt; greenlet -&gt; gevent  迭代器迭代时访问集合元素的一种方式，迭代器是一个可以记住遍历的位置的对象，迭代器对象从集合的第一个元素开始访问，直到所有的元素被访问完结束。迭代器只能往前不会后退。  可迭代对象  对list、tuple、str、dict、集合等类型的">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-03-06T06:15:25.339Z">
<meta property="article:modified_time" content="2020-03-06T06:15:25.339Z">
<meta property="article:author" content="CT">
<meta property="article:tag" content="python">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="daydaychen.github.io/2020/03/06/02-%E5%A4%9A%E4%BB%BB%E5%8A%A1-%E5%8D%8F%E7%A8%8B/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>python协程 | 宁静致远</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">宁静致远</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">this is a subtitle.</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="daydaychen.github.io/2020/03/06/02-%E5%A4%9A%E4%BB%BB%E5%8A%A1-%E5%8D%8F%E7%A8%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="CT">
      <meta itemprop="description" content="this is a desc.">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="宁静致远">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          python协程
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-03-06 14:15:25" itemprop="dateCreated datePublished" datetime="2020-03-06T14:15:25+08:00">2020-03-06</time>
            </span>

          
            <span id="/2020/03/06/02-%E5%A4%9A%E4%BB%BB%E5%8A%A1-%E5%8D%8F%E7%A8%8B/" class="post-meta-item leancloud_visitors" data-flag-title="python协程" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2020/03/06/02-%E5%A4%9A%E4%BB%BB%E5%8A%A1-%E5%8D%8F%E7%A8%8B/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2020/03/06/02-%E5%A4%9A%E4%BB%BB%E5%8A%A1-%E5%8D%8F%E7%A8%8B/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h4 id="协程"><a href="#协程" class="headerlink" title="协程"></a>协程</h4><blockquote>
<p>生成器 迭代器 装饰器 Python三大器</p>
</blockquote>
<blockquote>
<p>迭代器 -&gt; 生成器 -&gt; yield -&gt; greenlet -&gt; gevent</p>
</blockquote>
<h4 id="迭代器"><a href="#迭代器" class="headerlink" title="迭代器"></a>迭代器</h4><p>迭代时访问集合元素的一种方式，迭代器是一个可以记住遍历的位置的对象，迭代器对象从集合的第一个元素开始访问，直到所有的元素被访问完结束。迭代器只能往前不会后退。</p>
<ol>
<li>可迭代对象</li>
</ol>
<p>对list、tuple、str、dict、集合等类型的数据使用for…in…的循环语法从其中依次拿到数据进行使用，我们把这样的过程称为遍历，也叫<strong>迭代</strong>。</p>
<p>但是，是否所有的数据类型都可以放到for…in…的语句中，然后让for…in…每次从中取出一条数据供我们使用，即供我们迭代吗？</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">from collections import Iterable</span><br><span class="line"></span><br><span class="line">isinstance([11, 22, 33], Iterable)</span><br><span class="line">-&gt; True</span><br><span class="line"></span><br><span class="line">isinstance((11, 22, 33), Iterable)</span><br><span class="line">-&gt; True</span><br><span class="line"></span><br><span class="line">isinstance(100, Iterable)</span><br><span class="line">-&gt; False</span><br></pre></td></tr></table></figure>
<h5 id="类的迭代、迭代器的实现"><a href="#类的迭代、迭代器的实现" class="headerlink" title="类的迭代、迭代器的实现"></a>类的迭代、迭代器的实现</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">from collections import Iterable</span><br><span class="line">from collections import Iterator</span><br><span class="line"></span><br><span class="line">class Classmate(object):</span><br><span class="line">    def __init__(self):</span><br><span class="line">        self.names &#x3D; list()</span><br><span class="line">        self.current_num &#x3D; 0</span><br><span class="line">        </span><br><span class="line">    def add(self, name):</span><br><span class="line">        self.names.append(name)</span><br><span class="line">    </span><br><span class="line">    def __iter__(self):</span><br><span class="line">        &#39;&#39;&#39;如果想要一个对象成为一个可以迭代的对象，即可以使用for，那么必须实现__iter__方法&#39;&#39;&#39;</span><br><span class="line">        return self</span><br><span class="line">    </span><br><span class="line">    def __next__(self):</span><br><span class="line">         &#39;&#39;&#39;返回调用值&#39;&#39;&#39;</span><br><span class="line">        if self.current_num &lt; len(self.names):</span><br><span class="line">            ret &#x3D; self.names[self.current_num]</span><br><span class="line">            self.current_num +&#x3D; 1</span><br><span class="line">            return ret</span><br><span class="line">        else:</span><br><span class="line">            raise StopIteration</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">classmate &#x3D; Classmate()</span><br><span class="line"></span><br><span class="line">classmate.add(&quot;张三&quot;)</span><br><span class="line">classmate.add(&quot;李四&quot;)</span><br><span class="line">classmate.add(&quot;王五&quot;)</span><br><span class="line"></span><br><span class="line"># print(&quot;判断classmate是否是可以迭代的对象：&quot;,isinstance(classmate, Iterable))</span><br><span class="line"># classmate_iterator &#x3D; iter(classmate)</span><br><span class="line"># print(&quot;判断classmate_iterator是否是迭代器：&quot;,isinstance(classmate_iterator, Iterator)</span><br><span class="line"></span><br><span class="line">for name in classmate:</span><br><span class="line">    print(name)</span><br></pre></td></tr></table></figure>
<h5 id="Fibonacci的迭代器实现"><a href="#Fibonacci的迭代器实现" class="headerlink" title="Fibonacci的迭代器实现"></a>Fibonacci的迭代器实现</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">class Fibonacci(object):</span><br><span class="line">    def __init__(self, all_num):</span><br><span class="line">        self.all_num &#x3D; all_num</span><br><span class="line">        self.current_num &#x3D; 0</span><br><span class="line">        self.a &#x3D; 0</span><br><span class="line">        self.b &#x3D; 1</span><br><span class="line">    </span><br><span class="line">    def __iter__(self):</span><br><span class="line">        return self</span><br><span class="line">        </span><br><span class="line">    def __next__(self):</span><br><span class="line">        if self.current_num &lt; self.all_num:</span><br><span class="line">            ret &#x3D; self.a</span><br><span class="line">            </span><br><span class="line">            self.a, self.b &#x3D; self.b, self.a+self.b</span><br><span class="line">            self.current_num +&#x3D; 1</span><br><span class="line">            </span><br><span class="line">            return ret</span><br><span class="line">        else:</span><br><span class="line">            raise StopIteration</span><br><span class="line"></span><br><span class="line">fibo &#x3D; Fibonacci(10)</span><br><span class="line"></span><br><span class="line">for num in fibo:</span><br><span class="line">    print(num)</span><br></pre></td></tr></table></figure>

<h5 id="并不是只有for循环能接受可迭代对象"><a href="#并不是只有for循环能接受可迭代对象" class="headerlink" title="并不是只有for循环能接受可迭代对象"></a>并不是只有for循环能接受可迭代对象</h5><p>除了for循环能接受可迭代对象，list、tuple等也能接受</p>
<p><strong>iter</strong>()  -&gt;  <strong>next</strong>() -&gt; return </p>
<h4 id="生成器"><a href="#生成器" class="headerlink" title="生成器"></a>生成器</h4><p>生成器是一个特殊的迭代器</p>
<h5 id="应用1"><a href="#应用1" class="headerlink" title="应用1"></a>应用1</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">nums &#x3D; [x*2 for x in range(10)]</span><br><span class="line">-&gt; [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]</span><br><span class="line"></span><br><span class="line">nums &#x3D; (x*2 for x in range(10))</span><br><span class="line">-&gt; &lt;generator object &lt;genexpr&gt; at 0x7f7ec7071938&gt;</span><br></pre></td></tr></table></figure>

<p>列表推导式生成一个列表<br>生成器生成一个对象，不占用内存空间,可通过for循环调用</p>
<h5 id="应用2"><a href="#应用2" class="headerlink" title="应用2"></a>应用2</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">def create_num(all_num):</span><br><span class="line">    a, b &#x3D; 0, 1</span><br><span class="line">    current_num &#x3D; 0</span><br><span class="line">    while current_num &lt; all_num：</span><br><span class="line">        yield a     #如果一个函数中有yield语句，那么这个就不再是函数，而是一个生成器模板</span><br><span class="line">        a, b &#x3D; b, a+b</span><br><span class="line">        current_num +&#x3D; 1</span><br><span class="line"># 如果在调用create_num的时候，发现这个函数中由yield，那么此时不是调用函数，而是创建一个生成器对象。</span><br><span class="line">obj &#x3D; create_num(10)</span><br><span class="line"></span><br><span class="line">for num in obj:</span><br><span class="line">    print(num)</span><br></pre></td></tr></table></figure>

<h5 id="yield生成器获取return值"><a href="#yield生成器获取return值" class="headerlink" title="yield生成器获取return值"></a>yield生成器获取return值</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">def create_num(all_num):</span><br><span class="line">    a, b &#x3D; 0, 1</span><br><span class="line">    current_num &#x3D; 0</span><br><span class="line">    while current_num &lt; all_num:</span><br><span class="line">        yield a</span><br><span class="line">        a, b &#x3D; b, a+b</span><br><span class="line">        current_num +&#x3D; 1</span><br><span class="line">    return &quot;ok....&quot;</span><br><span class="line">    </span><br><span class="line">obj &#x3D; create_num(20)</span><br><span class="line"></span><br><span class="line">while True:</span><br><span class="line">    try:</span><br><span class="line">        ret &#x3D; next(obj)</span><br><span class="line">        print(ret)</span><br><span class="line">    except Exception as ret:</span><br><span class="line">        print(ret.value)</span><br><span class="line">        break</span><br></pre></td></tr></table></figure>

<h5 id="send-传递参数"><a href="#send-传递参数" class="headerlink" title="send()传递参数"></a>send()传递参数</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">def create_num(all_num):</span><br><span class="line">    a, b &#x3D; 0, 1</span><br><span class="line">    current_num &#x3D; 0</span><br><span class="line">    while current_num &lt; all_num:</span><br><span class="line">        ret &#x3D; yield a   # 右侧语句执行暂停，传参给next()</span><br><span class="line">        # send()将参数传过来，程序从暂停处开始执行，将传过来的参数赋给ret</span><br><span class="line">        print(&quot;ret:&quot;, ret)</span><br><span class="line">        a, b &#x3D; b, a+b</span><br><span class="line">        current_num +&#x3D; 1</span><br><span class="line">    </span><br><span class="line">obj &#x3D; create_num(20)</span><br><span class="line"></span><br><span class="line">ret &#x3D; next(obj) </span><br><span class="line">print(ret)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">ret &#x3D; obj.send(&quot;hahaahha&quot;)  #等同于next()，不同的是可以传参</span><br><span class="line"># send()一般不会放到第一次启动生成器，如果非要这么做，那么传递None</span><br><span class="line"># 再次运行到yield a，将a的值赋给ret</span><br><span class="line">print(ret)</span><br></pre></td></tr></table></figure>

<h3 id="使用yield完成多任务"><a href="#使用yield完成多任务" class="headerlink" title="使用yield完成多任务"></a>使用yield完成多任务</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">import time</span><br><span class="line"></span><br><span class="line">def task_1():</span><br><span class="line">    while True:</span><br><span class="line">        print(&quot;---1---&quot;)</span><br><span class="line">        time.sleep(0.1)</span><br><span class="line">        yield</span><br><span class="line">        </span><br><span class="line">def task_2():</span><br><span class="line">    while True:</span><br><span class="line">        print(&quot;---2---&quot;)</span><br><span class="line">        time.sleep(0.1)</span><br><span class="line">        yield</span><br><span class="line"></span><br><span class="line">def main():</span><br><span class="line">    t1 &#x3D; task_1()</span><br><span class="line">    t2 &#x3D; task_2()</span><br><span class="line">    # 先让t1运行一会，当t1中遇到yield的时候，返回此处</span><br><span class="line">    # 执行t2，当它遇到yield的时候，再次切换到t1中</span><br><span class="line">    # 这样t1&#x2F;t2&#x2F;t1&#x2F;t2的交替运行，最终实现了多任务...协程</span><br><span class="line">    while True:</span><br><span class="line">        next(t1)</span><br><span class="line">        next(t2)</span><br><span class="line"></span><br><span class="line">if __name__ &#x3D;&#x3D; &quot;__main__&quot;:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>

<h4 id="使用greenlet、gevent完成多任务"><a href="#使用greenlet、gevent完成多任务" class="headerlink" title="使用greenlet、gevent完成多任务"></a>使用greenlet、gevent完成多任务</h4><p>核心使用yield实现</p>
<p>$ pip3 install greenlet     # 安装greenlet</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">from greenlet import greenlet</span><br><span class="line">import time</span><br><span class="line"></span><br><span class="line">def test1():</span><br><span class="line">    while True:</span><br><span class="line">        print(&quot;---A---&quot;)</span><br><span class="line">        gr2.switch()</span><br><span class="line">        time.sleep(0.5)</span><br><span class="line">        </span><br><span class="line">def test2():</span><br><span class="line">    while True:</span><br><span class="line">        print(&quot;---B---&quot;)</span><br><span class="line">        gr1.switch()</span><br><span class="line">        time.sleep(0.5)</span><br><span class="line"></span><br><span class="line">gr1 &#x3D; greenlet(test1)</span><br><span class="line">gr2 &#x3D; greenlet(test2)</span><br><span class="line"></span><br><span class="line"># 切换到gr1中运行</span><br><span class="line">gr1.switch()</span><br></pre></td></tr></table></figure>

<p>$ pip3 install gevent</p>
<ul>
<li>依赖关系<br>协程 &lt;- 线程&lt;- 进程<br>遇到耗时操作进行切换</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">import gevent</span><br><span class="line"></span><br><span class="line">def f1(n):</span><br><span class="line">    for i in range(n):</span><br><span class="line">        print(gevent.getcurrent(), i)</span><br><span class="line">        gevent.sleep(0.5)</span><br><span class="line"></span><br><span class="line">def f2(n):</span><br><span class="line">    for i in range(n):</span><br><span class="line">        print(gevent.getcurrent(), i)</span><br><span class="line">        gevent.sleep(0.5)</span><br><span class="line"></span><br><span class="line">def f3(n):</span><br><span class="line">    for i in range(n):</span><br><span class="line">        print(gevent.getcurrent(), i)</span><br><span class="line">        gevent.sleep(0.5)</span><br><span class="line"></span><br><span class="line">g1 &#x3D; gevent.spawn(f1, 5)     #  生成yield对象 f:指定函数 5:指定传参 </span><br><span class="line">g2 &#x3D; gevent.spawn(f2, 5)</span><br><span class="line">g3 &#x3D; gevent.spawn(f3, 5)</span><br><span class="line">g1.join()   # 运行期间会耗时，自行切换到下一个对象</span><br><span class="line">g2.join()</span><br><span class="line">g3.join()</span><br></pre></td></tr></table></figure>

<h4 id="sleep补丁"><a href="#sleep补丁" class="headerlink" title="sleep补丁"></a>sleep补丁</h4><ul>
<li>协程使用代码示例<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">from gevent import monkey</span><br><span class="line">import gevent</span><br><span class="line">import random</span><br><span class="line">import time</span><br><span class="line"></span><br><span class="line"># 有耗时操作时需要</span><br><span class="line">monkey.patch_all()      # 将程序中用到的耗时操作的代码，换为gevent中自己实现的模块</span><br><span class="line"></span><br><span class="line">def coroutine_work(coroutine_name):</span><br><span class="line">    for i in range(10):</span><br><span class="line">        print(coroutine_name, i)</span><br><span class="line">        time.sleep(random.random()</span><br><span class="line"></span><br><span class="line"># 将多个join连接起来用一个元组实现</span><br><span class="line"># 等待元组中所有协程都完成后结束当前进程</span><br><span class="line">gevent.joinall([</span><br><span class="line">            gevent.spawn(coroutine_work, &quot;work1&quot;),</span><br><span class="line">            gevent.spawn(coroutine_work, &quot;work2&quot;)</span><br><span class="line">])</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h4 id="案例-并发下载器"><a href="#案例-并发下载器" class="headerlink" title="案例-并发下载器"></a>案例-并发下载器</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">from gevent import monkey</span><br><span class="line">import gevent</span><br><span class="line">import urllib.request</span><br><span class="line"></span><br><span class="line">monkey.patch_all()</span><br><span class="line"></span><br><span class="line">def downloader(img_name, img_url):</span><br><span class="line">    req &#x3D; urllib.request.urlopen(img_orl)</span><br><span class="line">    </span><br><span class="line">    img_content &#x3D; req.read()</span><br><span class="line">    </span><br><span class="line">    with open(img_name, &quot;wb&quot;) as f:</span><br><span class="line">        f.write(img_content)</span><br><span class="line">        </span><br><span class="line">def main():</span><br><span class="line">    gevent.joinall([</span><br><span class="line">                gevent.spawn(downlaoder, &quot;1.jpg&quot;, &quot;http:&#x2F;&#x2F;url&quot;),</span><br><span class="line">                gevent.spawn(downlaoder, &quot;1.jpg&quot;, &quot;http:&#x2F;&#x2F;url&quot;)</span><br><span class="line">    ])</span><br><span class="line"></span><br><span class="line">if __name__ &#x3D;&#x3D; &quot;__main__&quot;:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>

<h4 id="进程、线程、协程对比"><a href="#进程、线程、协程对比" class="headerlink" title="进程、线程、协程对比"></a>进程、线程、协程对比</h4><ul>
<li>有一个老板想要开个工厂进行生产某件商品</li>
<li>他需要画一些财力物力制作一条生产线，这个生产线上有很多的器件以及材料这些所有的为了能够生产商品而准备的资源称之为：<strong>进程</strong></li>
<li>只有生产线程时不能够进行生产的，所以老板需要找个工人来进行生产，这个工人能够利用这些材料最终一步步的将商品制作出来，这个来做事情的工人称之为：<strong>线程</strong></li>
<li>这个老板为了提高生产率，想到3种方法：<ol>
<li>在这条生产线上多找些工人，一起来做商品，这样效率是成倍增长，即<strong>单进程 多线程</strong>方式</li>
<li>老板发现这条生产线上的工人不是越多越好，因为一条生产线的资源以及材料毕竟有限，所以老板又花了写财力物力购置了一条生产线，然后再招些工人，这样效率又再一步提高了，即<strong>多进程 多线程</strong>方式</li>
<li>老板发现，现在已经有了很多条生产线，并且每条生产线上已经有很多工人了（即程序是多进程的，每个进程中又有多个线程），为了再次提高效率，老板想了个损招，规定：如果某个员工在上班时，临时没事或者再等待某些条件（比如等待另一个工人生产完某道工序之后，他才能再次工作），那么这个员工就利用这个时间去做其他的事情，那么也就是说：如果一个线程等待某些条件，可以充分利用这个时间去做其他事情，其实这就是：<strong>协程</strong>方式</li>
</ol>
</li>
</ul>
<h5 id="简单总结"><a href="#简单总结" class="headerlink" title="简单总结"></a>简单总结</h5><ol>
<li>进程是资源分配的单位</li>
<li>线程是操作系统调度的单位</li>
<li>进程切换需要的资源最大，效率很低</li>
<li>线程切换需要的资源一般，效率一般（不考虑GIL的情况下）</li>
<li>协程切换任务资源很小，效率高</li>
<li>多进程、多线程根据CPU核数不一样可能是并行的，但是协程是在一个线程中，所以是并发。</li>
</ol>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/python/" rel="tag"># python</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/03/06/03-%E7%AE%80%E5%8D%95web%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%AE%9E%E7%8E%B0/" rel="prev" title="简单web服务器python实现">
      <i class="fa fa-chevron-left"></i> 简单web服务器python实现
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/03/06/02-%E5%A4%9A%E4%BB%BB%E5%8A%A1-%E7%BA%BF%E7%A8%8B/" rel="next" title="python线程">
      python线程 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#协程"><span class="nav-number">1.</span> <span class="nav-text">协程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#迭代器"><span class="nav-number">2.</span> <span class="nav-text">迭代器</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#类的迭代、迭代器的实现"><span class="nav-number">2.1.</span> <span class="nav-text">类的迭代、迭代器的实现</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Fibonacci的迭代器实现"><span class="nav-number">2.2.</span> <span class="nav-text">Fibonacci的迭代器实现</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#并不是只有for循环能接受可迭代对象"><span class="nav-number">2.3.</span> <span class="nav-text">并不是只有for循环能接受可迭代对象</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#生成器"><span class="nav-number">3.</span> <span class="nav-text">生成器</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#应用1"><span class="nav-number">3.1.</span> <span class="nav-text">应用1</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#应用2"><span class="nav-number">3.2.</span> <span class="nav-text">应用2</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#yield生成器获取return值"><span class="nav-number">3.3.</span> <span class="nav-text">yield生成器获取return值</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#send-传递参数"><span class="nav-number">3.4.</span> <span class="nav-text">send()传递参数</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用yield完成多任务"><span class="nav-number"></span> <span class="nav-text">使用yield完成多任务</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#使用greenlet、gevent完成多任务"><span class="nav-number">1.</span> <span class="nav-text">使用greenlet、gevent完成多任务</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#sleep补丁"><span class="nav-number">2.</span> <span class="nav-text">sleep补丁</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#案例-并发下载器"><span class="nav-number">3.</span> <span class="nav-text">案例-并发下载器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#进程、线程、协程对比"><span class="nav-number">4.</span> <span class="nav-text">进程、线程、协程对比</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#简单总结"><span class="nav-number">4.1.</span> <span class="nav-text">简单总结</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="CT"
      src="/images/avatar.gif">
  <p class="site-author-name" itemprop="name">CT</p>
  <div class="site-description" itemprop="description">this is a desc.</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">16</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/daydaychen" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;daydaychen" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:ctt0120@foxmail.com" title="E-Mail → mailto:ctt0120@foxmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">CT</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.7.2
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.1.0/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-pjax@0/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/medium-zoom@1/dist/medium-zoom.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/velocity-animate@1/velocity.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/velocity-animate@1/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.getAttribute('pjax') !== null) {
      script.setAttribute('pjax', '');
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/valine@1/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : '9bBjpz3HRuKNuKNp7T27dFsT-gzGzoHsz',
      appKey     : 'k2pzqGWjkjrKxlFLQ3O0oqDn',
      placeholder: "Just go go",
      avatar     : 'robohash',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

    </div>
</body>
</html>
